<?php
class Easynote_Model_Book extends model {
  
    public $user_id = null;

    private $sqls = array(
        'get_all' => 'select `book_id`,`book_name`,(select count(1) from `mini_easynote_record` where `book_id` = `book`.`book_id` and `user_id` = [@user_id]) as `book_count` from `mini_easynote_book` as `book` where `user_id` = [@user_id] order by `created` asc;',
        'create'  => 'insert into `mini_easynote_book`(`book_id`,`book_name`,`user_id`,`created`,`updated`) values([@book_id],[@book_name],[@user_id],[@created],[@updated])',
        'update'  => 'update `mini_easynote_book` set `book_name` = [@book_name], `updated` = [@updated] where `book_id` = [@book_id] and `user_id` = [@user_id]',
        'delete'  => 'delete from `mini_easynote_book` where `book_id` = [@book_id] and `user_id` = [@user_id]',
        '_with_record' => 'delete from `mini_easynote_record` where `book_id` = [@book_id] and `user_id` = [@user_id]',
    );
    
    public function __construct(){
        parent::__construct();
    }
    
    //list
    public function get_all(){
        return mysql::fetch('book', $this->sqls['get_all'], array('user_id'=>$this->user_id));
    }
    
    //添加
    public function add($name){
        $created = $updated = time();
        $id = md5($name.$created);
        mysql::execute('book', $this->sqls['create'], array('book_id'=>$id, 'book_name'=>$name, 'user_id'=>$this->user_id, 'created'=>$created, 'updated'=>$updated));
        return $id;
    }
    
    //修改
    public function edit($id,$name){
        $updated = time();
        mysql::execute('book', $this->sqls['update'], array('book_id'=>$id, 'user_id'=>$this->user_id, 'book_name'=>$name, 'updated'=>$updated));
        return true;
    }

    //删除
    public function delete($id, $with_record = false){
        if($with_record){
            mysql::startTrans();
            mysql::execute('book', $this->sqls['delete'], array('book_id'=>$id));
            mysql::execute('record', $this->sqls['_with_record'], array('book_id'=>$id));
            mysql::commit();
            return true;
        }else{
            mysql::execute('book', $this->sqls['delete'], array('book_id'=>$id));
        }
    }
}